package com.zxl.app.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zxl.app.context.UserContext;
import com.zxl.common.exception.LoginException;
import com.zxl.common.model.pojo.SysMember;
import com.zxl.common.model.query.AppletsTokenMemberInfo;
import com.zxl.common.service.SysMemberService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zxw
 * @date 2023/4/1
 * token拦截器
 */
@Component
public class ApiTokenInterceptor implements HandlerInterceptor {
    @Resource
    private SysMemberService sysMemberService;

    /**
     * Authorization头名称
     */
    public static final String TOKEN_NAME = "api-access-token";


    /**
     * 拦截请求，无token返回
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UserContext.clearContext();
        String token = request.getHeader(TOKEN_NAME);
        SysMember member = sysMemberService.getOne(new QueryWrapper<SysMember>()
                .eq("token", token));
        if (member == null) {
            throw new LoginException(LoginException.PERMISSION_TOKEN_ERROR);
        }

        UserContext.setUserId(member.getId());
        AppletsTokenMemberInfo tokenMemberInfo = new AppletsTokenMemberInfo();
        BeanUtil.copyProperties(member, tokenMemberInfo);
        UserContext.setUserInfo(tokenMemberInfo);
        UserContext.setUser(member);
        return true;
    }


    /**
     * 清空用户上下文
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clearContext();
    }
}
